﻿"use strict";
/// <reference path="jquery-1.7-vsdoc.js" />
var language;
var fbLoginStatus = false;
var fbId = null;



function initButtons() {
    //    $("#createButton").click(function () {
    //        alert("CreateButton clicked");
    //    });

    //    $("#previewButton").click(function () {
    //        alert("Preview Button clicked");
    //    });

}

function deleteSong(songId) {
    ///perform a request
    $.get('../Song/Delete',
        { songId: songId }, function () {
            ///refreshed current page
            location.reload(true);
        });

}

//function getFbLoginStatus() {
//    FB.getLoginStatus(function (response) {
//        if (response.authResponse) {
//            fbLoginStatus = true;
//        } else {
//            // no user session available, someone you dont know
//        }
//        alert(fbLoginStatus);
//    });
//}

function initFacebook() {
    ///code for init fb api
    if (!$("#fb-root").length) {
        return;
    }

    window.fbAsyncInit = function () {
        ///response when javascript api is ready
        FB.init({
            appId: '140390589306756', // App ID
            //                channelURL: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            oauth: true, // enable OAuth 2.0
            xfbml: true  // parse XFBML
        });

        FB.Event.subscribe('auth.login', function (response) {
            login();
        });
        FB.Event.subscribe('auth.logout', function (response) {
            logout();
        });
        FB.getLoginStatus(function (response) {
            ///query login
            thisGetLoginStatus();
        });

        setFbProfile();



    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/fr_FR/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
}

/*---------------------------FB------------------------------*/

function setFbProfile() {
    //takes saved id and look for name and picture
    //has nothing to do with logged users
    if ($("#fbId").length) {
        var fbIds = $("#fbId").html().split('|');

        if (fbIds.length >= 0) {
            ///case more than 1 person
            for (var i = 0; i < fbIds.length; i++) {
                ///cycle through each Ids
                FB.api('/' + fbIds[i] + "/?fields=name,picture", function (response) {
                    $("#fbPictures").prepend("<img src=" + response.picture + " />");
                    $("#fbNames").prepend(response.name + "&nbsp;");

                    //                    $.logThis("from fb call back"+language);
                });
            }

            ///more than one, plural fbText
            if (fbIds.length > 1) {
                if (language == "fr-FR") {
                    $("#fbText").html("ont contribué à cette chanson");
                }
                else {
                    ///nothing to change in english
                    //                    $("#fbText").html("ont contribué à cette chanson");
                }
            }

        }
    }
}


function login() {
    ///event called when user is logged in
    FB.api('/me', function (response) {
        fbId = response.id;
        $.logThis("called back after login (login button clicked and user logged in through new window)");
        fillFBInfo(fbId);
    });
}

function logout() {
    //            alert('You have successfully logged out!');
    ///todo:get back to "login" fbbutton
}
function thisGetLoginStatus() {

    FB.api('/me', function (response) {

        ///cosole show either undefined(=notlogged) or an ind(=logged)
        fbId = response.id;
        fillFBInfo(fbId);


    });
}

function fillFBInfo(fbId) {
    ///either at satrup or from call back after login

    $.logThis("current logged facebook id user:" + fbId);
    if (fbId != null) {
        ///fill div used for identifying fb user in creating/editing song
        $("#SubmittedBy").attr("value", fbId);
        ///if logged, show picture and name
        FB.api('/' + fbId + "/?fields=name,picture", function (response) {
            fbId = response.id;
            $("#loggedFbPicture").attr("src", response.picture);
            $("#loggedFbPicture").show();
            $("#loggedFbName").html("&nbsp;&nbsp;" + response.name + $("#loggedFbName").html());
        });
        ///user logged, hide login button
        $("#fbLogingButton").hide();
        $("#fbTextWithLoginButton").hide();

    }
    else {
        ///user not logged, show connection button
        $("#fbLogingButton").show();
        $("#fbTextWithLoginButton").show();
    }
}

/*---------------------------FB------------------------------*/

function documentReady() {
    initTopbanner();
    ///set language in cookie
    language = $("html").attr("lang");

    //    setGoogleAnalytics();
    //    alert(fbLoginStatus);
    initFacebook();
    //    alert(fbId);

    initButtons();

    ///init filter box
    initFilterBox();


    if ($("#Content").length) {
        $("#Content").htmlarea(); // Initialize jHtmlArea's with all default values
        $("#Content_fr").htmlarea(); // Initialize jHtmlArea's with all default values
        $("#Content_en").htmlarea(); // Initialize jHtmlArea's with all default values
    }


    //    initTabs();




}

function initTopbanner() {
    var today = new Date();
    var dd = today.getDate();

    var i;

    if (dd <= 10) {
        i = 1;
    }
    else if (dd <= 20) {
        i = 2;
    }
    else if (dd <= 31) {
        i = 3;
    }
    $("#topImage").addClass("topImage" + i);
}



function addToFavorites(songId) {

    var songTitlesArray;

    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        songTitlesArray = JSON.parse(songTitles);
    }
        ///1st one
    else {
        songTitlesArray = new Array();
    }
    songTitlesArray.push(songId);
    $.jStorage.set("songTitlesFavorites", JSON.stringify(songTitlesArray));
    $("#removeFromFavButton").show();
    $("#addToFavButton").hide();

}

function removeFromFavorites(songId) {
    ///saves a new array without the removed song
    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        var songTitlesArray = JSON.parse(songTitles);

        for (var i = 0; i < songTitlesArray.length; i++) {
            if (songTitlesArray[i] == songId) {
                songTitlesArray.splice(i, 1);
            }
        }
        $.jStorage.set("songTitlesFavorites", JSON.stringify(songTitlesArray));
    }
        ///1st one
    else {
        alert("error");
    }
    $("#addToFavButton").show();
    $("#removeFromFavButton").hide();
}

function getSongTitles() {
    ///get song titles from database

    ///get from local first
    if ($.jStorage.get("songTitles")) {

        var songTitles = $.jStorage.get("songTitles");
        var songTitlesArray = JSON.parse(songTitles);
        for (var i = 0; i < songTitlesArray.length; i++) {

            ///fill list view
            var listItem = "<li>" +
                                "<a onclick=\"getSong('" + songTitlesArray[i] + "')\" >" + songTitlesArray[i].toUpperCase() + "</a>" +
                           "</li>";
            $("#listSongs").append(listItem);
            $("#listSongs").listview("refresh");
        }
    }

    ///then look online
    if (navigator.onLine) {
        $.get(language + '/mobile/getSongTitles', function (data) {

            ///check local
            var songTitlesArray;
            if ($.jStorage.get("songTitles")) {
                var songTitles = $.jStorage.get("songTitles");
                var songTitlesArray = JSON.parse(songTitles);

                if (data.length == songTitlesArray.length) {
                    ///no new song returns
                    $.logThis("no new song returns");
                    return;
                }
            }

            ///new songs,replace
            $("#listSongs").html("");
            $.logThis("new songs,replace");
            for (var i = 0; i < data.length; i++) {
                ///fill list view
                var listItem = "<li>" +
                                    "<a onclick=\"getSong('" + data[i] + "')\" >" + data[i].toUpperCase() + "</a>" +
                               "</li>";
                $("#listSongs").append(listItem);
                $("#listSongs").listview("refresh");
            }
            $.jStorage.set("songTitles", JSON.stringify(data));

        });
    }
    else {
        alert("user offline, reverting ot offline songs");
        $.mobile.changePage("#listViewPageFav", { transition: "slide" });
    }

}

function getAllMVC() {
    ///get song titles from database

    $("#songList").html("");
    $("#tabs-1").css("display", "block");
    $("#tabs-2").css("display", "none");
    $("#tabs-3").css("display", "none");
    $("#songContent").css("display", "none");

    $.get("../mobile/getSongTitles", function (data) {

        populateListViewMVC(data, "songList");

    });

}

function getFavorites() {
    ///get list of songs from favorites

    ///get from local first if exist
    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        var songTitlesArray = JSON.parse(songTitles);
        populateListView(songTitlesArray);
    }
    else {
        ///no song
        populateListView(null);
    }
};



function getFavoritesMVC() {
    ///get list of songs from favorites for MVC

    ///init
    $("#songListFavorites").html("");
    $("#tabs-1").css("display", "none");
    $("#tabs-2").css("display", "block");
    $("#tabs-3").css("display", "none");
    $("#songContent").css("display", "none");

    var noSong = "No song in favorite, go to all, go to a song, and click add to favorite";
    if (language == "fr-FR") {
        noSong = "Aucune chanson dans tes favoris, choisis une chanson et click sur Ajouter aux favoris";
    }



    ///get from local first if exist
    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        var songTitlesArray = JSON.parse(songTitles);
        if (songTitlesArray.length == 0) {
            $("#songListFavorites").html(noSong);
        }
        else {
            populateListViewMVC(songTitlesArray, "songListFavorites");
        }
    }
    else {
        $("#songListFavorites").html(noSong);
    }
};

function populateListViewMVC(songTitlesArray, listViewId) {

    for (var i = 0; i < songTitlesArray.length; i++) {
        if (songTitlesArray[i] != "") {
            //            $("#songContent").html($.jStorage.get(songTitlesArray[i]));

            ///fill list view
            var listItem =
                    "<li>" +
                        "<a href=\"../Songs/" + songTitlesArray[i] + "\" >" + songTitlesArray[i] + "</a>" +
                    "</li>";
            $("#" + listViewId).append(listItem);
        }
    }
}

function populateListView(songTitlesArray) {
    ///clear list
    $("#listSongsFavorites").html("");

    var noSong = "No song in favorite, go to all, go to a song, and click add to favorite";
    if ($("html").attr("lang") == "fr-FR") {
        noSong = "Aucune chanson dans tes favoris, choisis une chanson et click sur Ajouter aux favoris";
    }
    if (songTitlesArray == null || songTitlesArray.length == 0) {
        var listItem = "<li>" +
                        "<a href=\"#listViewPage\" >" + noSong + "</a>" +
                       "</li>";
        $("#listSongsFavorites").append(listItem);
        $("#listSongsFavorites").listview("refresh");
        return;
    }


    for (var i = 0; i < songTitlesArray.length; i++) {
        ///put in array only if content exist
        if (songTitlesArray[i] != "" && $.jStorage.get(songTitlesArray[i])) {
            $("#songContent").html($.jStorage.get(songTitlesArray[i]));

            ///fill list view
            var listItem = "<li>" +
                            "<a onclick=\"getSong('" + songTitlesArray[i] + "')\" >" + songTitlesArray[i].toUpperCase() + "</a>" +
                           "</li>";
            $("#listSongsFavorites").append(listItem);
            $("#listSongsFavorites").listview("refresh");
        }
    }
}

function getSongTitlesArray(songTitles) {
    return songTitles.split('|');
}



var songCount = 1;
var i = 0;



function suckSongs(month) {

    ///clear output
    $("#outPut").html("<div class=\"result\">results:</div><div class=\"resultHidden\"></div>");

    songCount = 1;
    ///http://ssijciedropsy.blogspot.com/
    //range : 2009_04_01 -------> 2011_09_01
    ///model link : http://ssijciedropsy.blogspot.com/2011_09_01_archive.html

    var link = "http://ssijciedropsy.blogspot.com/" + month + "_01_archive.html";
    $(".result").before("<hr/><h1>" + link + "</h1>");
    getData(link);
}

//function doAgain(){
// var link = "http://ssijciedropsy.blogspot.com/2009_0" + 5 + "_01_archive.html";
//    $(".result").before("<hr/><h1>" + link + "</h1>");
//    getData(link);
//}


// filter out some nasties
function filterData(data) {
    //    data = data.replace('/<?/body[^>]*>/g', '');
    //        data = data.replace(/[r|n]+/g,'');
    //        data = data.replace(/<--[Ss]*?-->/g,'');
    //        data = data.replace(/<noscript[^>]*>[Ss]*?</noscript>/g,'');
    //        data = data.replace(/<script[^>]*>[Ss]*?</script>/g,'');
    //        data = data.replace(/<script.*/>/,'');
    //    data = data.replace(/<body[^>]*>[\s\S]*?<\/body>/gi, '');
    data = data.replace("<body class=\"loading\">", '');
    data = data.replace("</body>");
    data = data.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');



    return data;
}


function linkMaker(year, month) {
    var link = "http://ssijciedropsy.blogspot.com/" + year + "_" + month + "_01_archive.html"
    return link;
}


function getData(link) {
    $.logThis("doing:" + link);
    var yqlLink = "http://query.yahooapis.com/v1/public/yql?" +
    "q=select%20*%20from%20html%20where%20url%3D%22" + link +
    "%22&format=xml'&callback=?";

    $.ajax({
        type: 'GET',
        url: yqlLink,
        dataType: 'json',
        success: function (returnData) {
            $.logThis("callbacked");
            if (returnData.results[0]) {
                var filteredData = filterData(returnData.results[0]);
                $(".resultHidden").html(filteredData);


                var cleanData = $("div.post.hentry");

                if (cleanData.length > 0) {
                    $.each(cleanData, function (index, value) {
                        $(".result").before("<hr/><h1>" + songCount++ + "</h1>");
                        $(".result").before(value);
                    });
                }

                //clear returnData
                $(".resultHidden").html("");
            } else {
                var errormsg = '<p>Error: could not load the page.</p>';
                //            container.html(errormsg);
                $.logThis(errormsg);
            }
        },
        data: {},
        async: false
        //        crossDomain:true
    });



}


function pushSongs() {

    var songTitles = new Array();
    var songLinks = new Array();
    var songContents = new Array();

    ///a post representing a song in ssij
    $(".post.hentry").each(
        function () {
            var title = $($(this).find("a")[1]).html();
            songTitles.push(title);

            ///take whats inside the object and add object around
            var link = "<object>" + $($(this).find("object")[0]).html() + "</object>";
            songLinks.push(link);

            var content = $($(this).find("p")[0]).html();
            songContents.push(content);
        }
    );

    $.ajax({
        type: 'post',
        traditional: true,
        data: {
            SongTitles: songTitles,
            SongLinks: songLinks,
            SongContents: songContents
        }
    });
}

///replace characters
function cleanHtml(stringToClean) {

    stringToClean = replaceAll(stringToClean, "<br>", "\n");
    stringToClean = replaceAll(stringToClean, "<em>", "");
    stringToClean = replaceAll(stringToClean, "</em>", "");

    return stringToClean;
}

function replaceAll(strToClean, oldStr, newStr) {
    while (strToClean.indexOf(oldStr) >= 0) {
        strToClean = strToClean.replace(oldStr, newStr);
    }
    return strToClean;
}

//function goOffline() {

//    $.get(language + '/mobile/gooffline', function (data) {

//        for (var i = 0; i < data.length; i++) {

//            ///fill list view
//            var listItem = "<li class=\"ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-g\" data-theme=\"g\">" +
//            "<div class=\"ui-btn-inner ui-li\">" +
//            "<div class=\"ui-btn-text\">" +
//            "<a class=\"ui-link-inherit\" onclick=\"getSong('" + data[i].SongId + "')\" >" + data[i].SongId + "</a>" +
//            "</div>" +
//            "<span class=\"ui-icon ui-icon-arrow-r ui-icon-shadow\"></span>" +
//            "</div>" +
//            "</li>";
//            $("#listSongs").append(listItem);

//            ///fill local storage
//            $.jStorage.set(data[i].SongId, data[i].Content);
//        }
//    });
//};

function getSong(songId) {
    ///retrieve content and fill divs
    ///look offline first then, look online

    $("#songId").html(songId);
    ///show loading... in content
    $("#songContent").html("loading...");

    ///check local
    if ($.jStorage.get(songId)) {
        var song = $.jStorage.get(songId);
        var htmlContent = createFavButtons(song) + "<h1>" + song.SongId + "</h1><br/>" + createSongLinkHtml(song) + song.Content;

        $("#songContent").html(htmlContent);
    }
    else {
        ///perform a request
        $.get(language + '/mobile/GetSongContent',
        { songId: songId },
        function (song) {
            var htmlContent = createFavButtons(song) + "<h1>" + song.SongId + "</h1><br/>" + createSongLinkHtml(song) + song.Content;
            $("#songContent").html(htmlContent);
            ///set song in local storage
            $.jStorage.set(songId, song);
        });
    }

    ///
    $.mobile.changePage("#songPage", { transition: "slide" });
}

function getSongMVC(songId) {
    ///retrieve content and fill divs in mvc3 mode

    ///look offline first then, look online
    $("#tabs-1").css("display", "none");
    $("#tabs-2").css("display", "none");
    $("#songContent").css("display", "block");
    $("#songId").html(songId);
    ///show loading... in content
    $("#songContent").html("loading...");

    ///check local
    if ($.jStorage.get(songId)) {
        var song = $.jStorage.get(songId);
        var htmlContent = createMVCContent(song);
        htmlContent += "<h2>" + song.SongId + "</h2><br/>" + createSongLinkHtml(song) + song.Content;
        $("#songContent").html(htmlContent);
    }
    else {
        ///perform a request
        $.get('../mobile/GetSongContent',
        { songId: songId },
        function (song) {
            var htmlContent = createMVCContent(song);
            htmlContent += "<h2>" + song.SongId + "</h2><br/>" + createSongLinkHtml(song) + song.Content;
            $("#songContent").html(htmlContent);
            ///set song in local storage
            $.jStorage.set(songId, song);
        });
    }

    ///
    //    $.mobile.changePage("#songPage", { transition: "slide" });
}

function createMVCContent(song) {
    language = $("html").attr("lang");
    var displayAddButton = true;
    var addFavLink = "Add to favorites";
    var remFavLink = "Remove from favorites";
    var editLink = "<a href=\"../Song/Edit/" + song.SongId + "\">Edit</a>";
    var shareLink = "Share";
    var submittedBy = " submitted this song<br/>";
    if (language == "fr-FR") {
        addFavLink = "Ajouter aux favoris";
        remFavLink = "Enlever des favoris";
        editLink = "<a href=\"../Song/Edit/" + song.SongId + "\">Editer</a>";
        shareLink = "Partager";
        submittedBy = " a partagé cette chanson<br/>";
    }
    var author = "Anonymous";
    if (song.SubmittedBy != "" && song.SubmittedBy != undefined) {
        author = "<div id=\"fbId\" class=\"hiddenField\">" + song.SubmittedBy + "</div>" +
                 "<div id=\"fbPictures\"></div>" +
                 "<div id=\"fbNames\" ></div>" +
                 "<div id=\"fbText\" >" + submittedBy + "</div>";
    }


    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        var songTitlesArray = JSON.parse(songTitles);
        for (var i = 0; i < songTitlesArray.length; i++) {
            if (song.SongId == songTitlesArray[i]) {
                displayAddButton = false;
            }
        }
    }

    var htmlContent;
    if (displayAddButton) {
        htmlContent =
        "<a id=\"addToFavButton\" href=\"javascript:addToFavorites('" + song.SongId + "');\">" + addFavLink + "</a>" +
        "<a id=\"removeFromFavButton\" style=\"display:none;\" href=\"javascript:removeFromFavorites('" + song.SongId + "');\">" + remFavLink + "</a>&nbsp;|&nbsp;" + editLink + "&nbsp;|&nbsp;" + shareLink + "<br/>" +
        "<div id=\"fbProfile\">" + author + "<div/>" +
        "<br/>";
    }
    else {
        htmlContent =
        "<a id=\"addToFavButton\" style=\"display:none;\" href=\"javascript:addToFavorites('" + song.SongId + "');\">" + addFavLink + "</a>" +
        "<a id=\"removeFromFavButton\" href=\"javascript:removeFromFavorites('" + song.SongId + "');\">" + remFavLink + "</a>&nbsp;|&nbsp;" + editLink + "&nbsp;|&nbsp;" + shareLink + "<br/>" +
        "<div id=\"fbProfile\">" + author + "<div/>" +
        "<br/>";
    }

    return htmlContent;
}

function createFavButtons(song) {
    var addFavLink = "Add to favorites";
    var remFavLink = "Remove from favorites";
    if (language == "fr-FR") {
        addFavLink = "Ajouter aux favoris";
        remFavLink = "Enlever des favoris";
    }


    var displayAddButton = true;

    if ($.jStorage.get("songTitlesFavorites")) {
        var songTitles = $.jStorage.get("songTitlesFavorites");
        var songTitlesArray = JSON.parse(songTitles);
        for (var i = 0; i < songTitlesArray.length; i++) {
            if (song.SongId == songTitlesArray[i]) {
                displayAddButton = false;
            }
        }
    }

    var htmlContent;
    if (displayAddButton) {
        htmlContent =
        "<a id=\"addToFavButton\" data-icon=\"plus\" data-role=\"button\" href=\"javascript:addToFavorites('" + song.SongId + "');\" data-theme=\"c\" class=\"ui-btn ui-btn-icon-left ui-btn-corner-all ui-shadow ui-btn-up-c\">" +
        "<span class=\"ui-btn-inner ui-btn-corner-all\">" +
        "<span class=\"ui-btn-text\">" + addFavLink + "</span>" +
        "<span class=\"ui-icon ui-icon-plus ui-icon-shadow\"></span></span></a>" +
        "<a id=\"removeFromFavButton\" style=\"display:none;\" data-icon=\"minus\" data-role=\"button\" href=\"javascript:removeFromFavorites('" + song.SongId + "');\" data-theme=\"c\" class=\"ui-btn ui-btn-icon-left ui-btn-corner-all ui-shadow ui-btn-up-c\">" +
        "<span class=\"ui-btn-inner ui-btn-corner-all\">" +
        "<span class=\"ui-btn-text\">" + remFavLink + "</span><span class=\"ui-icon ui-icon-minus ui-icon-shadow\"></span></span></a>";
    }
    else {
        htmlContent =
        "<a id=\"addToFavButton\" style=\"display:none;\" data-icon=\"plus\" data-role=\"button\" href=\"javascript:addToFavorites('" + song.SongId + "');\" data-theme=\"c\" class=\"ui-btn ui-btn-icon-left ui-btn-corner-all ui-shadow ui-btn-up-c\">" +
        "<span class=\"ui-btn-inner ui-btn-corner-all\">" +
        "<span class=\"ui-btn-text\">" + addFavLink + "</span><span class=\"ui-icon ui-icon-plus ui-icon-shadow\"></span></span></a>" +
        "<a id=\"removeFromFavButton\" data-icon=\"minus\" data-role=\"button\" href=\"javascript:removeFromFavorites('" + song.SongId + "');\" data-theme=\"c\" class=\"ui-btn ui-btn-icon-left ui-btn-corner-all ui-shadow ui-btn-up-c\">" +
        "<span class=\"ui-btn-inner ui-btn-corner-all\">" +
        "<span class=\"ui-btn-text\">" + remFavLink + "</span><span class=\"ui-icon ui-icon-minus ui-icon-shadow\"></span></span></a>";
    }

    return htmlContent;
}

function createSongLinkHtml(song) {
    ///sub function, detect if not mobile, then show link
    if (!jQuery.browser.mobile) {
        return song.Link + "<br/>";
    }
    else {
        return "";
    }
}

(function (a) { jQuery.browser.mobile = /android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)) })(navigator.userAgent || navigator.vendor || window.opera);

//function setGoogleAnalytics() {
//    var _gaq = _gaq || [];
//    _gaq.push(['_setAccount', 'UA-26321122-1']);
//    _gaq.push(['_trackPageview']);

//    (function () {
//        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//    })();
//}

function initFilterBox() {

    if (!$("#filter").length) {
        return;
    }

    //init filter box
    (function ($) {
        // custom css expression for a case-insensitive contains()
        jQuery.expr[':'].Contains = function (a, i, m) {
            return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
        };


        function listFilter(header, list) { // header is any element, list is an unordered list
            // create and add the filter form to the header
            var form = $("<form>").attr({ "class": "filterform", "action": "#" }),
        input = $("<input>").attr({ "class": "filterinput", "type": "text" });
            $(form).append(input).appendTo(header);

            $(input)
      .change(function () {
          var filter = $(this).val();
          if (filter) {
              // this finds all links in a list that contain the input,
              // and hide the ones not containing the input while showing the ones that do
              //              $(list).find("span:not(:Contains(" + filter + ")),a:not(:Contains(" + filter + "))").parent().hide();
              //              $(list).find("span:Contains(" + filter + "),a:Contains(" + filter + ")").parent().show();
              $(list).find("a:not(:Contains(" + filter + "))").parent().hide();
              $(list).find("a:Contains(" + filter + ")").parent().show();
          } else {
              $(list).find("li").slideDown();
          }
          return false;
      })
    .keyup(function () {
        // fire the above change event after every letter
        $(this).change();
    });
        }


        //ondomready
        $(function () {
            listFilter($("#filter"), $("#songList"));
        });
    }(jQuery));




}

//function initTabs() {



//    $(function () {
//        $("#tabs").tabs();
//    });

//    $('a[href|="#tabs-1"]').click(function () {
//        window.location = window.location.hostname + "/" + language + "/Songs/All";
//    });
//    $('a[href|="#tabs-2"]').click(function () {
//        window.location = window.location.hostname + "/" + language + "/Songs/Favorites";
//    });
//    $('a[href|="#tabs-3"]').click(function () {
//        window.location = window.location.hostname + "/" + language + "/Songs/Create";
//    });

//}



jQuery.logThis = function (text) {
    if ((window['console'] !== undefined)) {
        ///specific capokun log
        console.log("Capokun|" + text);
    }
}